package com.example.com.daervideo.fragments.video;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.example.com.daervideo.R;

import com.example.com.daervideo.activitys.EarnMoneyActivity;
import com.example.com.daervideo.activitys.MainActivity;
import com.example.com.daervideo.databinding.FragmentVideoBinding;
import com.example.com.daervideo.databinding.ItemVideoBinding;
import com.example.com.daervideo.entity.BaseListEntity;
import com.example.com.daervideo.entity.UserData;
import com.example.com.daervideo.entity.VideoEntity;
import com.example.com.daervideo.fragments.BaseListFragmnet;
import com.example.com.daervideo.initerface.ApiService;
import com.example.com.daervideo.myViews.MyTXVodPlayer;
import com.example.com.daervideo.popuwindow.GiftPpwindow;
import com.example.com.daervideo.myViews.MyLayoutManager;
import com.example.com.daervideo.popuwindow.ZuanNumPpWindow;
import com.example.com.daervideo.utils.DensityUtil;
import com.example.com.daervideo.utils.RetrofitClient;
import com.example.com.daervideo.vm.fragments.VideoFragmentViewModel;


import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.BaseUrlExternalStrageDir;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

import com.example.com.daervideo.BR;
import com.example.com.transcribeeditpublish.activity.VideoEditActivity;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodPlayConfig;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.tencent.rtmp.TXLiveConstants.NET_STATUS_VIDEO_HEIGHT;
import static com.tencent.rtmp.TXLiveConstants.NET_STATUS_VIDEO_WIDTH;
import static com.tencent.rtmp.TXLiveConstants.PLAY_EVT_PLAY_END;

/**
 * Created by i7-1 on 2018/12/3.
 * <p>
 */

public class VideoFragment extends BaseListFragmnet<FragmentVideoBinding, VideoFragmentViewModel> implements View.OnClickListener {


    private List<VideoEntity> lists;
    private LinearLayoutManager manager;
    private String TAG = "video";
    private String url = "http://flv2.bn.netease.com/videolib3/1611/28/GbgsL3639/SD/movie_index.m3u8";
    //  private String url = "http://1253146644.vod2.myqcloud.com/2707fe83vodgzp1253146644/96d58ab65285890784259728224/HJgdCT1kFfIA.mp4";
    private TXVodPlayer currentPlayer;
    private TXCloudVideoView currentVideoView;
    private boolean isVisibleToUser;
    private MainActivity mainActivity;
    private BottomSheetDialog mBottomSheetDialog;
    private View mBottomSheetView;
    private RecyclerView messageRV;
    private GiftPpwindow giftPpwindow;
    private ZuanNumPpWindow zuanNumPpWindow;
    private TXVodPlayConfig mConfig;
    private ApiService apiService;
    private ArrayList mVodPlayers = new ArrayList();
    private int mCurrentIndex;
    private float windowHeight;
    private float windowidth;

    public void clear() {
        if (currentPlayer != null) {
            currentPlayer.stopPlay(true);
            currentPlayer = null;
        }
        if (currentVideoView != null) {
            currentVideoView.removeVideoView();
            currentVideoView.onDestroy();
            currentVideoView = null;
        }
        lists.clear();
        page = 1;
        pageSize = 10;
    }

    @Override
    public int initContentView() {
        return R.layout.fragment_video;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public VideoFragmentViewModel initViewModel() {
        KLog.e("initViewModel");
        return new VideoFragmentViewModel(context);
    }

    @Override
    protected void getNetData(int page, int pageSize) {
        getVideoList(page, pageSize);
    }

    @Override
    protected TwinklingRefreshLayout getRefreshLayout() {
        return binding.vInclude.refreshLayout;
    }

    /**
     * replace videoFragment  initData重新执行
     */
    @Override
    public void initData() {
        super.initData();
        KLog.e("initData = " + DensityUtil.getWindowHeight(context) + ", w= " + DensityUtil.getWindowidth(context));
        windowHeight = DensityUtil.getWindowHeight(context);
        windowidth = DensityUtil.getWindowidth(context);
        mainActivity = (MainActivity) this.context;
        apiService = RetrofitClient.getInstance().create(ApiService.class);

        initVideo();
        initListener();
        initBeHavior();
        initPpwindow();
    }


    private void initPpwindow() {
        giftPpwindow = new GiftPpwindow(context);
        giftPpwindow.setData();
        zuanNumPpWindow = new ZuanNumPpWindow(context);
    }

    private void initBeHavior() {
        mBottomSheetDialog = new BottomSheetDialog(context);
        mBottomSheetView = LayoutInflater.from(context).inflate(R.layout.layout_bottom_message, null, false);
        mBottomSheetDialog.setContentView(mBottomSheetView);
        Window window = mBottomSheetDialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.dimAmount = 0;
        window.setAttributes(params);
        mBottomSheetDialog.getWindow().getDecorView().findViewById(R.id.design_bottom_sheet).setBackgroundResource(R.color.transparent);
        messageRV = mBottomSheetView.findViewById(R.id.m_rv);
        messageRV.setLayoutManager(new LinearLayoutManager(context));
        messageRV.setAdapter(new MessageAdapter(context, null));
    }

    public void showMessagePpWindow(int position) {
        mBottomSheetDialog.show();

    }

    private void showGiftPpWindow(int position) {
        giftPpwindow.setID(position);
        giftPpwindow.showAtLocation(mainActivity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    private void showzuanNumPpWindow(int position) {
        zuanNumPpWindow.setID(position);
        zuanNumPpWindow.showAtLocation(mainActivity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);

    }

    private void toUserFragment(int position) {
        mainActivity.setCurrentUser(position);
        RxBus.getDefault().post(1);
    }

    private void pauseOrResumeVideo(VideoHolder holder) {
        if (currentPlayer != null) {
            if (currentPlayer.isPlaying()) {
                currentPlayer.pause();
                holder.itemBinding.pauseImg.setVisibility(View.VISIBLE);
            } else {
                currentPlayer.resume();
                holder.itemBinding.pauseImg.setVisibility(View.GONE);
            }
        }
    }

    private void initVideo() {
        binding.vInclude.recyclerview.setNestedScrollingEnabled(false);
        // binding.videoRv.setItemViewCacheSize(3);
        manager = new MyLayoutManager(context, OrientationHelper.VERTICAL, false);
        binding.vInclude.recyclerview.setLayoutManager(manager);
        binding.vInclude.recyclerview.setAdapter(new VideoAdapter());
        binding.vInclude.refreshLayout.startRefresh();
    }


    private TXVodPlayer initPlayer() {
        MyTXVodPlayer mLivePlayer = new MyTXVodPlayer(context);
        mLivePlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);
        TXVodPlayConfig mConfig = initVideoConfig();
        mLivePlayer.setConfig(mConfig);
        mLivePlayer.setVodListener(new ITXVodPlayListener() {
            @Override
            public void onPlayEvent(TXVodPlayer txVodPlayer, int event, Bundle bundle) {
                if (event == PLAY_EVT_PLAY_END) {
                    if (mCurrentIndex == lists.size() - 1) {
                        return;
                    }
                    if (mCurrentIndex == lists.size() - 2) {
                        binding.vInclude.refreshLayout.startLoadMore();
                    }
                    binding.vInclude.recyclerview.smoothScrollToPosition(mCurrentIndex + 1);
                }
                int height = txVodPlayer.getHeight();
                MyTXVodPlayer player = (MyTXVodPlayer) txVodPlayer;
                if (height != 0 && player.getRenderMode() != TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION && height < windowHeight / 2) {
                    KLog.e("height =" + height + " ,windowHeight=" + windowHeight);
                    txVodPlayer.pause();
                    player.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);
                    txVodPlayer.resume();
                }
            }

            @Override
            public void onNetStatus(TXVodPlayer txVodPlayer, Bundle bundle) {


            }
        });

        return mLivePlayer;
    }

    @NonNull
    private TXVodPlayConfig initVideoConfig() {
        if (mConfig != null) {
            return mConfig;
        }
        //指定一个本地mp4缓存目录
        mConfig = new TXVodPlayConfig();
        String cache = BaseUrlExternalStrageDir.getBaseUrl() + File.separator + "selectCache";

        mConfig.setCacheFolderPath(cache);
        //指定本地最多缓存多少文件，避免缓存太多数据
        mConfig.setMaxCacheItems(10);
        return mConfig;
    }

    private class VideoAdapter extends RecyclerView.Adapter<VideoHolder> {
        @Override
        public VideoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ItemVideoBinding bind = DataBindingUtil.bind(LayoutInflater.from(context).inflate(R.layout.item_video, parent, false));
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) bind.txVideo.getLayoutParams();
            layoutParams.height = (int) (DensityUtil.getWindowidth(context) * 16);
            bind.txVideo.setLayoutParams(layoutParams);
            Log.e(TAG, "onCreateViewHolder");
            return new VideoHolder(bind);
        }

        @Override
        public void onBindViewHolder(final VideoHolder holder, final int position) {
            String tag = (String) holder.itemBinding.getRoot().getTag();
            Log.e("Video", tag + " position = " + position);
            holder.itemBinding.getRoot().setTag("" + position);
            setListener(holder, position);
            TXVodPlayer txVodPlayer;
            if (tag == null) {
                txVodPlayer = initPlayer();
                mVodPlayers.add(txVodPlayer);
            } else if (Integer.valueOf(tag) != position) {
                holder.getPlayer().stopPlay(true);
                mVodPlayers.remove(holder.getPlayer());
                holder.itemBinding.txVideo.removeVideoView();
                holder.itemBinding.txVideo.onDestroy();
                txVodPlayer = initPlayer();
                mVodPlayers.add(txVodPlayer);
            } else {
                txVodPlayer = holder.getPlayer();
            }
            txVodPlayer.setPlayerView(holder.itemBinding.txVideo);
            holder.setPlayer(txVodPlayer);
            //txVodPlayer.setAutoPlay(false);
            holder.setIsPause(false);
            holder.itemBinding.cover.setVisibility(View.VISIBLE);
            Glide.with(holder.itemView.getContext()).load(lists.get(position).getCoverUrl()).centerCrop().into(holder.itemBinding.cover);
            holder.itemBinding.executePendingBindings();
        }


        @Override
        public void onViewAttachedToWindow(VideoHolder holder) {
            super.onViewAttachedToWindow(holder);
            String tag = (String) holder.itemBinding.getRoot().getTag();
            Log.e(TAG, "Attached=" + tag + ",chirlds=" + binding.vInclude.recyclerview.getChildCount() +
                    "isPlaying=" + holder.getPlayer().isPlaying());
            currentPlayer = holder.getPlayer();
            currentVideoView = holder.itemBinding.txVideo;
            int index = Integer.valueOf(tag);
            mCurrentIndex = index;
            mainActivity.setCurrentUser(lists.get(index).getUserId());
            if (holder.isPause()) {
                holder.getPlayer().resume();
                holder.itemBinding.pauseImg.setVisibility(View.GONE);
            } else {
                holder.getPlayer().startPlay(lists.get(index).getPlayUrl());
                holder.getPlayer().setPlayListener(new ITXLivePlayListener() {
                    @Override
                    public void onPlayEvent(int i, Bundle bundle) {

                    }

                    @Override
                    public void onNetStatus(Bundle bundle) {

                    }
                });
            }

            holder.itemBinding.cover.setVisibility(View.GONE);
            holder.setIsPause(false);
        }

        @Override
        public void onViewDetachedFromWindow(VideoHolder holder) {
            String tag = (String) holder.itemBinding.getRoot().getTag();
            super.onViewDetachedFromWindow(holder);
            holder.getPlayer().pause();
            holder.setIsPause(true);
            Log.e(TAG, "onViewDetachedFromWindow=" + tag + ",chirlds=" +
                    binding.vInclude.recyclerview.getChildCount() + "isPlaying=" + holder.getPlayer().isPlaying());
        }

        @Override
        public int getItemCount() {
            return lists == null ? 0 : lists.size();
        }

        private void setListener(final VideoHolder holder, final int position) {
            holder.itemBinding.showMesage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showMessagePpWindow(position);
                }
            });
            holder.itemBinding.gift.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showGiftPpWindow(position);
                }
            });
            holder.itemBinding.zuanNum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showzuanNumPpWindow(position);
                }
            });
            holder.itemBinding.userIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toUserFragment(position);
                }
            });
            holder.itemBinding.txVideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pauseOrResumeVideo(holder);
                }
            });
            holder.itemBinding.pauseImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pauseOrResumeVideo(holder);
                }
            });
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (currentPlayer != null) {
            currentPlayer.pause();
        }
        Log.e(TAG, "onPause");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e(TAG, "setUserVisibleHint=" + isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (currentPlayer != null) {
            if (isVisibleToUser) {
                currentPlayer.resume();
            } else {
                currentPlayer.pause();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (currentPlayer != null && isVisibleToUser) {
            currentPlayer.resume();
        }
        Log.e(TAG, "onResume" + " currentPlayer= " + currentPlayer + ",isVisibleToUser" + isVisibleToUser);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        clear();
        binding.vInclude.recyclerview.getRecycledViewPool().clear();
        super.onDestroy();
    }


    private void initListener() {
        binding.headTab.setListener(this);
        binding.zhaungqian.setOnClickListener(this);
        // binding.zhaungqian.setOnClickLisenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            //热门
            case R.id.hot:
                break;
            //关注
            case R.id.attention:
                break;
            case R.id.zhaungqian:
                startActivity(new Intent(context, EarnMoneyActivity.class));
                break;
        }
    }

    private void getVideoList(final int page, int pageSize) {
        apiService.getVideoList(page, pageSize).compose(RxUtils.bindToLifecycle(this)) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<BaseListEntity>>() {
                    @Override
                    public void accept(BaseResponse<BaseListEntity> response) throws Exception {
                        if (response.getCode() == 0) {
                            if (page == 1) {
                                getRefreshLayout().finishRefreshing();
                                lists = response.getData().getPageItems();
                                binding.vInclude.setSize(lists.size());
                                binding.vInclude.recyclerview.getAdapter().notifyDataSetChanged();
                            } else {
                                getRefreshLayout().finishLoadmore();
                                List items = response.getData().getPageItems();
                                if (items.size() == 0) {
                                    ToastUtils.showShort("到底了！");
                                } else {
                                    lists.addAll(items);
                                    binding.vInclude.recyclerview.getAdapter().notifyDataSetChanged();
                                }
                            }
                        } else {
                            ToastUtils.showShort(response.getMsg());
                        }
                        mainActivity.dismissDialog();
                    }
                }, new Consumer<ResponseThrowable>() {
                    @Override
                    public void accept(ResponseThrowable throwable) throws Exception {
                        if (page == 1) {
                            getRefreshLayout().finishRefreshing();
                        } else {
                            getRefreshLayout().finishLoadmore();
                        }
                        ToastUtils.showShort(throwable.message);
                        throwable.printStackTrace();
                    }
                });
    }
}